package provisioner.algorithm;

import java.util.*;

public class FrequencyComparator implements Comparator<String> {
   public static final int MOST_FIRST = 0;
   public static final int LEAST_FIRST = 1;

   private Map<String,Integer> amountMap;
   private int mode;

   public FrequencyComparator(Map<String,Integer> amountMap) {
      this(amountMap,LEAST_FIRST);
   }

   public FrequencyComparator(Map<String,Integer> amountMap,int mode) {
      this.amountMap = amountMap;
      this.mode = mode;
   }

   public int compare(String r1, String r2) {
      Integer ct1 = amountMap.get(r1);
      if (ct1 == null) ct1 = new Integer(0);
      Integer ct2 = amountMap.get(r2);
      if (ct2 == null) ct2 = new Integer(0);
   
      int ret = 0;

      if (ct1 < ct2) {
         ret =  -1;
      } else if (ct1 == ct2) {
         ret = r1.compareTo(r2);
      } else {
         ret = 1;
      }
    
      if (this.mode == MOST_FIRST) {
         ret = -ret;
      }
      return ret;
   }
}
